package com.dms.modules.user.controller;

import com.dms.common.api.ApiResponse;
import com.dms.common.security.SecurityUtils;
import com.dms.modules.user.dto.UserBehaviorDTO;
import com.dms.modules.user.service.UserBehaviorService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.Max;
import javax.validation.constraints.NotBlank;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/api/v1/user/behavior")
@Api(tags = "用户行为接口")
@RequiredArgsConstructor
@Validated
@PreAuthorize("isAuthenticated()")
public class UserBehaviorController {
    
    private final UserBehaviorService userBehaviorService;
    
    @PostMapping("/browse")
    @ApiOperation("记录用户浏览行为")
    public ApiResponse<Boolean> recordUserBrowse(@Valid @RequestBody UserBehaviorDTO dto) {
        Long userId = SecurityUtils.getCurrentUserId();
        return ApiResponse.success(userBehaviorService.recordUserBrowse(userId, dto));
    }
    
    @PostMapping("/search")
    @ApiOperation("记录用户搜索")
    public ApiResponse<Void> recordUserSearch(
            @RequestParam @NotBlank(message = "搜索关键词不能为空") 
            @ApiParam("搜索关键词") String keyword) {
        Long userId = SecurityUtils.getCurrentUserId();
        userBehaviorService.recordUserSearch(userId, keyword);
        return ApiResponse.success();
    }
    
    @GetMapping("/category-preferences")
    @ApiOperation("获取用户分类偏好")
    public ApiResponse<List<Map<String, Object>>> getUserCategoryPreferences(
            @RequestParam(required = false, defaultValue = "5") Integer limit) {
        Long userId = SecurityUtils.getCurrentUserId();
        return ApiResponse.success(userBehaviorService.getUserCategoryPreferences(userId, limit));
    }
    
    @GetMapping("/search/history")
    @ApiOperation("获取用户搜索历史")
    public ApiResponse<List<String>> getSearchHistory(
            @RequestParam(defaultValue = "10") 
            @Max(value = 100, message = "每页最多显示100条记录") 
            @ApiParam("限制数量") int limit) {
        Long userId = SecurityUtils.getCurrentUserId();
        return ApiResponse.success(userBehaviorService.getUserRecentSearches(userId, limit));
    }
    
    @DeleteMapping("/search/history")
    @ApiOperation("清除搜索历史")
    public ApiResponse<Void> clearSearchHistory() {
        Long userId = SecurityUtils.getCurrentUserId();
        userBehaviorService.clearUserSearchHistory(userId);
        return ApiResponse.success();
    }
} 